package myJs.common.loadSample

import myJs.myPkg.{Lightbox, SwalOptions, layer}
import myJs.myPkg.jquery.$
import org.scalajs.dom.{Event, File, FileList, FileReader, FormData, XMLHttpRequest, html, window}
import slinky.core.{FunctionalComponent, SyntheticEvent, TagElement}
import slinky.core.annotations.react
import slinky.core.facade.Hooks.useState
import slinky.core.facade.React
import slinky.web.html._

import scala.concurrent.{Future, Promise}
import myJs.Implicits._
import myJs.api.Api
import myJs.assets
import myJs.cps.Style
import org.scalajs.dom

import scala.scalajs.js.Dynamic.{global => g}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import slinky.web.SyntheticMouseEvent
import typings.csstype.csstypeStrings

/**
 * Created by yz on 21/1/2022
 */
@react object LabAppendSelectCp {

  case class Props(files: List[File], filesChange: List[File] => Unit, serverFiles: List[String],
                   serverFilesChange: List[String] => Unit,
                   id: String)

  val component = FunctionalComponent[Props] { props =>

    val inputRef = React.createRef[html.Input]

    val viewUrl = s"${Api.apiUrl}/panda/tool/viewFile"

    object FTool {

      def openFile = () => {
        inputRef.current.click()
      }

      def viewImage = () => {
        val y = inputRef.current
        val fileOp = $(y).prop("files")
        fileOp.foreach { curFiles =>
          val fileList = curFiles.asInstanceOf[FileList]
          val fs = fileList.map { file =>
            val promise = Promise[String]()
            val reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onloadend = (e) => {
              val uri = reader.result.toString
              promise.success(uri)
            }
            promise.future
          }
          val curFileNames = fileList.map(_.name).toList
          Future.sequence(fs).map { curUris =>
            val filterFiles = props.files.filterNot { f =>
              curFileNames.contains(f.name)
            }
            props.filesChange(filterFiles ::: fileList.toList)
          }

        }
      }

      def removeFile(curI: Int) = () => {
        props.filesChange(props.files.removedByI(curI))
      }

      def removeServerFile(curI: Int) = () => {
        props.serverFilesChange(props.serverFiles.removedByI(curI))
      }

      def uploadFile(file: File) = (e: SyntheticMouseEvent[a.tagType#RefType]) => {
        val jq = $(e.target).parents("a")
        Api.uploadFile(file) { response =>
          jq.attr("href", s"${viewUrl}?filePath=${response.filePath}")
        }
        ()
      }

    }

    val serverViewUrl = s"${Api.apiUrl}/panda/sample/viewFile"

    div(style := Style(display = csstypeStrings.flex),
      props.serverFiles.zipWithIndex.map { case (file, curI) =>
        div(key := s"${curI}", style := Style(marginRight = 20, width = 100, display = csstypeStrings.`inline-block`),
          div(style := Style(width = 100, height = 100, border = "3 px solid #fff",
            boxShadow = " 0 .1rem 1rem .25rem rgba(0,0,0,.05)", borderRadius = "0.475rem", display = csstypeStrings.flex,
            flexDirection = csstypeStrings.column),
            className := "myImgDiv",
            div(style := Style(display = csstypeStrings.flex, justifyContent = csstypeStrings.`flex-end`),
              label(style := STool.removeLabel,
                className := "btn-icon myLabel", onClick := FTool.removeServerFile(curI),
                i(style := Style(), className := "fa fa-remove myRemove")
              ),
            ),
            div(style := Style(display = csstypeStrings.flex, justifyContent = csstypeStrings.center),
              i(style := Style(fontSize = 25), className := "fa fa-file-o")
            ),
            a(style := Style(display = csstypeStrings.flex, alignItems = csstypeStrings.`flex-end`, flex = 1,
              justifyContent = csstypeStrings.center, marginBottom = 5, paddingLeft = 5, paddingRight = 5,
              textAlign = csstypeStrings.center,wordBreak = csstypeStrings.`break-all`),
              href := s"${serverViewUrl}?&fileName=${file}&sampleId=${props.id}",
              className := "filePath", target := "_blank",
              span(className := "filePathA", title := file,
                file
              )
            )

          ),

        )
      },
      props.files.zipWithIndex.map { case (file, curI) =>
        div(key := s"${curI}", style := Style(marginRight = 20, width = 100, display = csstypeStrings.`inline-block`),
          div(style := Style(width = 100, height = 100, border = "3 px solid #fff",
            boxShadow = " 0 .1rem 1rem .25rem rgba(0,0,0,.05)", borderRadius = "0.475rem", display = csstypeStrings.flex,
            flexDirection = csstypeStrings.column),
            className := "myImgDiv",
            div(style := Style(display = csstypeStrings.flex, justifyContent = csstypeStrings.`flex-end`),
              label(style := STool.removeLabel,
                className := "btn-icon myLabel", onClick := FTool.removeFile(curI),
                i(style := Style(), className := "fa fa-remove myRemove")
              ),
            ),
            div(style := Style(display = csstypeStrings.flex, justifyContent = csstypeStrings.center),
              i(style := Style(fontSize = 25), className := "fa fa-file-o")
            ),

            a(style := Style(display = csstypeStrings.flex, alignItems = csstypeStrings.`flex-end`, flex = 1,
              justifyContent = csstypeStrings.center, marginBottom = 5, paddingLeft = 5, paddingRight = 5,
              textAlign = csstypeStrings.center, wordBreak = csstypeStrings.`break-all`),
              href := s"${viewUrl}",
              className := "filePath",
              onClick := FTool.uploadFile(file),
              target := "_blank",
              span(className := "filePathA", title :=  file.name,
                file.name
              )

            )

          ),

        )
      },
      input(`type` := "file", style := Style(display = csstypeStrings.none), ref := inputRef, multiple, onChange := FTool.viewImage),

      div(style := Style(marginRight = 20, width = 100, display = csstypeStrings.`inline-block`),
        div(style := Style(width = 100, height = 100, border = "3 px solid #fff",
          boxShadow = " 0 .1rem 1rem .25rem rgba(0,0,0,.05)", borderRadius = "0.475rem", display = csstypeStrings.flex,
          flexDirection = csstypeStrings.column),
          className := "myImgDiv", onClick := FTool.openFile,
          div(style := Style(display = csstypeStrings.flex, alignItems = csstypeStrings.`flex-end`, flex = 1,
            justifyContent = csstypeStrings.center, backgroundImage = s"url('${Api.images}/addimg.png')", backgroundRepeat = "no-repeat",
            backgroundSize = "cover", cursor = csstypeStrings.pointer),
          )

        ),

      ),

    )

  }

  object STool {

    val imgWidth = 100
    val imgHeight = 100

    val imgDiv = Style(marginRight = 20)

    val addImgDiv = Style(backgroundRepeat = "no-repeat", backgroundSize = "cover",
      position = csstypeStrings.relative, display = csstypeStrings.`inline-block`, cursor = csstypeStrings.pointer)

    def img(uri: String) = Style(width = imgWidth, height = imgHeight, border = "3 px solid #fff",
      boxShadow = " 0 .1rem 1rem .25rem rgba(0,0,0,.05)", borderRadius = "0.475rem")

    val removeLabel = Style(display = csstypeStrings.`inline-flex`, alignItems = csstypeStrings.center,
      justifyContent = csstypeStrings.center, borderRadius = "50%",
      boxShadow = " 0 .5rem 1.5rem .5rem rgba(0,0,0,.075)", transform = "translate(50%,-50%)", width = 20,
      height = 20)

  }


}
